package com.yxkj.railservicer.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.suke.widget.SwitchButton;
import com.yxkj.railservicer.R;
import com.yxkj.railservicer.application.MyApplication;
import com.yxkj.railservicer.util.ChannelStatusConsts;
import com.yxkj.railservicer.util.ContentUtil;
import com.yxkj.railservicer.util.HeartBreakUtil;
import com.yxkj.railservicer.util.JSONUtil;
import com.yxkj.railservicer.util.SPUtil;
import com.yxkj.railservicer.util.ScreenUtils;
import com.yxkj.railservicer.util.SysApplicationUtil;

import java.io.IOException;
import java.util.Set;

import cn.jpush.android.api.JPushInterface;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import android.util.Log;

public class SettingActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = "TAG";
    private TextView tv_setting_name;
    private TextView tv_setting_telnumber;
    private TextView tv_setting_num;
    private Button btn_setting_exit;
    private ImageView iv_main_setting;
    private ImageView iv_main_back;
    private TextView tv_title;
    private LinearLayout ll_setting_complete;

    private OkHttpClient client;
    private JSONUtil jsonUtil;

    private SwitchButton switch_button;
    private SwitchButton switch_statue;

    private ProgressDialog dialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting);
        ScreenUtils.setTranStatus(this, true, Color.parseColor("#2387f5"));
        SysApplicationUtil.getInstance().addActivity(this);
        initData();
        initEvent();
    }

    private void initEvent() {
        tv_title.setText("设置");
        iv_main_setting.setVisibility(View.INVISIBLE);
        iv_main_back.setOnClickListener(this);
        btn_setting_exit.setOnClickListener(this);
        ll_setting_complete.setOnClickListener(this);

        tv_setting_name.setText(SPUtil.getString(this, "name"));
        tv_setting_telnumber.setText(SPUtil.getString(this, "phoneNo"));
    }

    private void initData() {
        tv_setting_name = (TextView) findViewById(R.id.tv_setting_name);
        tv_setting_telnumber = (TextView) findViewById(R.id.tv_setting_telnumber);
        tv_setting_num = (TextView) findViewById(R.id.tv_setting_num);
        tv_title = (TextView) findViewById(R.id.tv_title);
        btn_setting_exit = (Button) findViewById(R.id.btn_setting_exit);
        iv_main_setting = (ImageView) findViewById(R.id.iv_main_setting);
        iv_main_back = (ImageView) findViewById(R.id.iv_main_back);
        ll_setting_complete = (LinearLayout) findViewById(R.id.ll_setting_complete);

        switch_button = (SwitchButton) findViewById(R.id.switch_button);
        switch_statue = (SwitchButton) findViewById(R.id.switch_statue);

        client = new OkHttpClient();
        jsonUtil = new JSONUtil();

        if (status != null && status == 5001) {
            switch_button.setChecked(true);
            SPUtil.setString(this, "isBusy", "开启");
            JPushInterface.resumePush(this);
        } else {
            switch_button.setChecked(false);
            SPUtil.setString(this, "isBusy", "关闭");
            JPushInterface.stopPush(this);
        }

        String isVoice = SPUtil.getString(this, "isVoice");
        if ("开启".equals(isVoice)) {
            switch_statue.setChecked(true);
            JPushInterface.setSilenceTime(SettingActivity.this, 23, 59, 0, 1);

        } else if ("关闭".equals(isVoice)) {
            switch_button.setChecked(false);
            JPushInterface.setSilenceTime(SettingActivity.this, 23, 59, 23, 59);
        } else {
            switch_statue.setChecked(true);
            JPushInterface.setSilenceTime(SettingActivity.this, 23, 59, 0, 1);
        }

        switchData();

        switchStatue();

        getOrder();
//        SPUtil.setBoolean(this, "isChecked", switch_button.isChecked());
    }

    //声音震动
    private void switchStatue() {
        switch_statue.setOnCheckedChangeListener(new SwitchButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(SwitchButton view, boolean isChecked) {

                if (isChecked) {
                    Toast.makeText(SettingActivity.this, "开启", Toast.LENGTH_SHORT).show();
                    JPushInterface.setSilenceTime(SettingActivity.this, 23, 59, 0, 1);
                    SPUtil.setString(SettingActivity.this, "isVoice", "开启");
                } else {
                    Toast.makeText(SettingActivity.this, "关闭", Toast.LENGTH_SHORT).show();
                    JPushInterface.setSilenceTime(SettingActivity.this, 23, 59, 23, 59);
                    SPUtil.setString(SettingActivity.this, "isVoice", "关闭");
                }
            }
        });
    }


    //接单按钮
    private void switchData() {
        switch_button.setOnCheckedChangeListener(new SwitchButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(SwitchButton view, boolean isChecked) {

                if (isChecked) {
//                    Toast.makeText(SettingActivity.this, "开启", Toast.LENGTH_SHORT).show();
                    Log.e(TAG, "开启服务+++++++++++++");
                    SPUtil.setString(SettingActivity.this, "isBusy", "开启");
                    JPushInterface.resumePush(SettingActivity.this);
                    HeartBreakUtil.setWorkStack(client, SettingActivity.this, ChannelStatusConsts.CHANNEL_STATUS_WORK);
                } else {
//                    Toast.makeText(SettingActivity.this, "关闭", Toast.LENGTH_SHORT).show();
                    SPUtil.setString(SettingActivity.this, "isBusy", "关闭");
                    JPushInterface.stopPush(SettingActivity.this);
                    HeartBreakUtil.setWorkStack(client, SettingActivity.this, ChannelStatusConsts.CHANNEL_STATUS_REST);
                    Log.e(TAG, "关闭服务+++++++++++++");
                }
            }
        });
    }

    private String completeOrdersToday;
    private static Integer status;

    private void getOrder() {
        dialog = ProgressDialog.show(this, "提示", "正在连接服务器，请稍后");
        Request request = new Request.Builder()
                .addHeader("token", SPUtil.getString(this, "token"))
                .url(ContentUtil.countOrder_url)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                toast("服务器繁忙，请稍后再试");
                dismiss();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String jsonData = response.body().string();
                if (jsonUtil.validate(jsonData)) {
                    JSONObject jsonObject = JSON.parseObject(jsonData);
                    if (jsonObject.getBoolean("success")) {
                        completeOrdersToday = jsonObject.getJSONObject("data").getString("completeOrdersToday");
                        status = jsonObject.getJSONObject("data").getInteger("status");
                        //Log.e("ee","=======取服务人员状态========"+jsonObject.getJSONObject("data").getInteger("status"));
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {


                                tv_setting_num.setText(completeOrdersToday);
                                if (status != null && status == 5001) {
                                    switch_button.setChecked(true);
                                } else {
                                    switch_button.setChecked(false);
                                }
                                SPUtil.setBoolean(MyApplication.getContext(), "isChecked", switch_button.isChecked());
                                dialog.dismiss();
                            }
                        });
                    } else {
                        toast(jsonObject.getString("message"));
                        dismiss();
                    }
                }
                Log.e(TAG, "查询总订单联网成功" + jsonData);
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_main_back:
                finish();
                break;
            case R.id.btn_setting_exit:
                exit();
                break;
            case R.id.ll_setting_complete:
                Intent intent = new Intent(SettingActivity.this, CompleteActivity.class);
                startActivity(intent);
                break;
        }
    }

    private void exit() {

        JPushInterface.stopPush(MyApplication.getContext());
        Log.d(TAG, "退出登录，停止极光推送");
        dialog = ProgressDialog.show(this, "提示", "正在退出");
        String token = SPUtil.getString(this, "token");
        HeartBreakUtil.sendHeartBreakPacket(client, SettingActivity.this, ChannelStatusConsts.CHANNEL_STATUS_REST);

        new HeartBreakUtil().stopRepeatTask("YW_HEART_BREAK_EVENT");

        Request request = new Request.Builder()
                .url(ContentUtil.quit_url)
                .addHeader("token",token)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                toast("服务器繁忙，请稍后再试");
                dismiss();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String jsonData = response.body().string();
                if (jsonUtil.validate(jsonData)) {
                    JSONObject jsonObject = JSON.parseObject(jsonData);
                    if (jsonObject.getBoolean("success")) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Intent intent = new Intent(SettingActivity.this, LoginActivity.class);
                                startActivity(intent);
//                                JPushInterface.stopPush(SettingActivity.this);
                                SysApplicationUtil.getInstance().exit();
                                SPUtil.exit(SettingActivity.this);
                                finish();
                            }
                        });
                    } else {
                        toast(jsonObject.getString("message"));
                    }
                }
                dismiss();
                Log.e("TAG", "退出成功" + jsonData);
            }
        });
    }

    private void toast(final String string) {
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(SettingActivity.this, string, Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void dismiss() {
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                dialog.dismiss();
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        SysApplicationUtil.getInstance().deleteActivity(this);
    }
}
